<template>
  <div class="problem-edit-container">
    <a-card class="general-card">
      <template #title>
        {{ isEdit ? '编辑题目' : '创建题目' }}
      </template>
      
      <a-steps :current="currentStep">
        <a-step title="基本信息" description="填写题目基本信息" />
        <a-step title="判题用例" description="添加判题用例" />
        <a-step title="完成" description="保存题目" />
      </a-steps>

      <!-- 步骤一：基本信息 -->
      <div v-if="currentStep === 0" class="step-content">
        <a-form
          ref="formRef"
          :model="problemForm"
          layout="vertical"
          @submit="handleNextStep"
        >
          <a-form-item
            field="title"
            label="题目标题"
            required
            :rules="[{ required: true, message: '请输入题目标题' }]"
          >
            <a-input
              v-model="problemForm.title"
              placeholder="请输入题目标题"
              allow-clear
            />
          </a-form-item>

          <a-form-item
            field="difficulty"
            label="难度"
            required
            :rules="[{ required: true, message: '请选择难度' }]"
          >
            <a-select v-model="problemForm.difficulty" placeholder="请选择难度">
              <a-option value="EASY">简单</a-option>
              <a-option value="MEDIUM">中等</a-option>
              <a-option value="HARD">困难</a-option>
            </a-select>
          </a-form-item>

          <a-form-item
            field="tags"
            label="标签"
          >
            <a-select
              v-model="problemForm.tags"
              placeholder="请选择标签"
              multiple
            >
              <a-option
                v-for="tag in tagStore.tagList"
                :key="tag.id"
                :value="tag.id"
              >
                {{ tag.name }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item
            field="judgeConfig.time_limit"
            label="时间限制(ms)"
            required
            :rules="[
              { required: true, message: '请输入时间限制' },
              { type: 'number', min: 0, message: '时间限制必须大于0' }
            ]"
          >
            <a-input-number
              v-model="problemForm.judgeConfig.time_limit"
              placeholder="请输入时间限制(ms)"
              min="0"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item
            field="judgeConfig.memory_limit"
            label="内存限制(KB)"
            required
            :rules="[
              { required: true, message: '请输入内存限制' },
              { type: 'number', min: 0, message: '内存限制必须大于0' }
            ]"
          >
            <a-input-number
              v-model="problemForm.judgeConfig.memory_limit"
              placeholder="请输入内存限制(KB)"
              min="0"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item
            field="content"
            label="题目内容"
            required
            :rules="[{ required: true, message: '请输入题目内容' }]"
          >
            <MdEditor
              style="width: 100%;"
              :value="problemForm.content"
              :onChange="(value) => (problemForm.content = value)"
            />
          </a-form-item>

          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit">下一步</a-button>
              <a-button @click="cancelEdit">取消</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 步骤二：判题用例 -->
      <div v-else-if="currentStep === 1" class="step-content">
        <div class="judge-case-header">
          <h3>判题用例列表</h3>
          <a-button type="primary" @click="addJudgeCase">
            添加用例
          </a-button>
        </div>

        <a-empty v-if="!problemForm.judgeCaseList || problemForm.judgeCaseList.length === 0" description="暂无判题用例">
          <template #image>
            <icon-file />
          </template>
        </a-empty>

        <div v-else class="judge-case-list">
          <a-collapse>
            <a-collapse-item
              v-for="(item, index) in (problemForm.judgeCaseList || [])"
              :key="index"
              :header="`用例 ${index + 1}`"
            >
              <div class="judge-case-item">
                <a-form layout="vertical">
                  <a-form-item field="input" label="输入">
                    <a-textarea
                      v-model="item.input"
                      placeholder="请输入测试用例输入内容"
                      :auto-size="{ minRows: 3, maxRows: 5 }"
                    />
                  </a-form-item>
                  <a-form-item field="output" label="输出">
                    <a-textarea
                      v-model="item.output"
                      placeholder="请输入期望的输出内容"
                      :auto-size="{ minRows: 3, maxRows: 5 }"
                    />
                  </a-form-item>
                </a-form>
                <div class="judge-case-actions">
                  <a-button type="text" status="danger" @click="removeJudgeCase(index)">
                    删除
                  </a-button>
                </div>
              </div>
            </a-collapse-item>
          </a-collapse>
        </div>

        <div class="step-actions">
          <a-space>
            <a-button @click="currentStep--">上一步</a-button>
            <a-button type="primary" @click="handleNextStep">
              下一步
            </a-button>
          </a-space>
        </div>
      </div>

      <!-- 步骤三：完成 -->
      <div v-else-if="currentStep === 2" class="step-content">
        <a-result
          status="success"
          :title="isEdit ? '题目已更新，请确认提交' : '题目已创建，请确认提交'"
        >
          <template #extra>
            <a-space>
              <a-button @click="currentStep--">上一步</a-button>
              <a-button type="primary" @click="submitProblem" :loading="submitting">
                提交
              </a-button>
            </a-space>
          </template>
          
          <!-- 题目摘要展示 -->
          <a-descriptions
            title="题目摘要"
            :column="{ xs: 1, sm: 2, md: 2 }"
            :data="[
              { label: '标题', value: problemForm.title },
              { label: '难度', value: getDifficultyText(problemForm.difficulty || 'EASY') },
              { label: '时间限制', value: `${problemForm.judgeConfig?.time_limit || 2000} ms` },
              { label: '内存限制', value: `${problemForm.judgeConfig?.memory_limit || 256} KB` },
              { label: '判题用例', value: `${problemForm.judgeCaseList?.length || 0} 个` },
              { label: '标签', value: getTagsText(problemForm.tags) }
            ]"
          />
        </a-result>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import MdEditor from '@/components/MdEditor.vue'
import { addProblemApi, updateProblemApi, getProblemVoByIdApi } from '@/api/problem/problem'
import { IconFile } from '@arco-design/web-vue/es/icon'
import { useTagStore } from '@/stores/tag'

const route = useRoute()
const router = useRouter()
const formRef = ref()
const currentStep = ref(0)
const submitting = ref(false)
const tagStore = useTagStore()

// 判断是否为编辑模式
const isEdit = computed(() => route.params.id !== undefined)

// 初始化表单数据
const problemForm = reactive<API.Problem.ProblemAddRequest>({
  title: '',
  content: '',
  judgeCaseList: [],
  difficulty: 'MEDIUM',
  judgeConfig: {
    time_limit: 2000,
    memory_limit: 256
  },
  tags: [1]
})

// 难度文本转换
const getDifficultyText = (difficulty: string) => {
  switch (difficulty) {
    case 'EASY':
      return '简单'
    case 'MEDIUM':
      return '中等'
    case 'HARD':
      return '困难'
    default:
      return '未知'
  }
}

// 标签文本转换
const getTagsText = (tags: number[] | undefined) => {
  if (!tags || tags.length === 0) {
    return '暂无标签'
  }
  return tags.map(tagId => tagStore.getTagNameById(tagId)).join('、')
}

// 获取题目详情
const fetchProblemDetail = async (id: number) => {
  try {
    const res = await getProblemVoByIdApi(id)
    if (res.code === 0 && res.data) {
      const problem = res.data
      
      // 填充表单数据
      problemForm.title = problem.title || ''
      problemForm.content = problem.content || ''
      problemForm.difficulty = problem.difficulty || 'MEDIUM'
      
      // 处理judgeConfig
      if (problem.judgeConfig) {
        problemForm.judgeConfig = {
          time_limit: Number(problem.judgeConfig.time_limit) || 2000,
          memory_limit: Number(problem.judgeConfig.memory_limit) || 256
        }
      }
      
      // 标签处理
      if (problem.tagsList && Array.isArray(problem.tagsList)) {
        problemForm.tags = problem.tagsList.map(tag => tag.id)
      }

      // 判题用例处理
      if (problem.judgeCaseList && Array.isArray(problem.judgeCaseList)) {
        problemForm.judgeCaseList = problem.judgeCaseList.map(caseItem => ({
          input: caseItem.input,
          output: caseItem.output
        }))
      }
    } else {
      Message.error(res.message || '获取题目详情失败')
    }
  } catch (error) {
    console.error('获取题目详情失败', error)
    Message.error('获取题目详情失败')
  }
}

// 处理下一步操作
const handleNextStep = async () => {
  if (currentStep.value === 0) {
    try {
      // 验证表单
      await formRef.value.validate()
      currentStep.value++
    } catch (errors) {
      console.log('表单验证失败', errors)
    }
  } else {
    currentStep.value++
  }
}

// 添加判题用例
const addJudgeCase = () => {
  // 确保judgeCaseList已初始化
  if (!problemForm.judgeCaseList) {
    problemForm.judgeCaseList = []
  }
  problemForm.judgeCaseList.push({
    input: '',
    output: ''
  })
}

// 删除判题用例
const removeJudgeCase = (index: number) => {
  // 安全检查
  if (problemForm.judgeCaseList && problemForm.judgeCaseList.length > index) {
    problemForm.judgeCaseList.splice(index, 1)
  }
}

// 提交题目
const submitProblem = async () => {
  submitting.value = true
  
  try {
    if (isEdit.value) {
      // 更新题目
      const updateData: API.Problem.ProblemUpdateRequest = {
        id: Number(route.params.id),
        content: problemForm.content,
        difficulty: problemForm.difficulty,
        judgeConfig: problemForm.judgeConfig,
        tags: problemForm.tags,
        judgeCaseList: problemForm.judgeCaseList
      }
      
      const res = await updateProblemApi(updateData)
      if (res.code === 0 && res.data) {
        Message.success('更新题目成功')
        router.push('/admin/problem')
      } else {
        Message.error(res.message || '更新题目失败')
      }
    } else {
      // 创建题目
      const submitData: API.Problem.ProblemAddRequest = {
        ...problemForm,
        difficulty: problemForm.difficulty || 'MEDIUM',
        judgeCaseList: problemForm.judgeCaseList || []
      }
      
      const res = await addProblemApi(submitData)
      if (res.code === 0 && res.data) {
        Message.success('创建题目成功')
        router.push('/admin/problem')
      } else {
        Message.error(res.message || '创建题目失败')
      }
    }
  } catch (error) {
    console.error(isEdit.value ? '更新题目失败' : '创建题目失败', error)
    Message.error(isEdit.value ? '更新题目失败' : '创建题目失败')
  } finally {
    submitting.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  router.push('/admin/problem')
}

// 初始化
onMounted(async () => {
  // 获取标签列表
  await tagStore.fetchAllTags()
  
  if (isEdit.value && route.params.id) {
    fetchProblemDetail(Number(route.params.id))
  }
})
</script>

<style scoped>
.general-card {
  margin-bottom: 20px;
}

.step-content {
  margin-top: 24px;
}

.judge-case-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.judge-case-list {
  margin-bottom: 16px;
}

.judge-case-item {
  position: relative;
}

.judge-case-actions {
  position: absolute;
  top: 0;
  right: 0;
}

.step-actions {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
</style> 